<template>
  <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
    <FormItem label="标题" prop="title">
      <Input v-model="formValidate.title" placeholder="请输入物品名称"></Input>
    </FormItem>

    <Row>
      <Col span="8">
        <FormItem label="类别" prop="cate_id">
          <Select v-model="formValidate.cate_id" style="width:200px">
            <Option v-for="zone in kindData" :value="zone.id" :key="zone.id">{{ zone.label }}</Option>
          </Select>
        </FormItem>
      </Col>

      <Col span="8">
        <FormItem label="起拍价" prop="init_price">
          <InputNumber
            :max="99999"
            :min="1"
            v-model="formValidate.init_price"
            :formatter="value => `$ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
            :parser="value => value.replace(/\$\s?|(,*)/g, '')"
            style="width: 150px"
          />
        </FormItem>
      </Col>
      <Col span="8">
        <FormItem label="加价幅度" prop="min_gap">
          <InputNumber
            :max="99999"
            :min="1"
            v-model="formValidate.min_gap"
            :formatter="value => `$ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
            :parser="value => value.replace(/\$\s?|(,*)/g, '')"
            style="width: 150px"
          />
        </FormItem>
      </Col>
    </Row>

    <FormItem label="拍卖时间" prop="start_time">
      <DatePicker
        :value="dateRange"
        type="datetimerange"
        @on-change="handleDate"
        format="yyyy-MM-dd HH:mm:ss"
        placeholder="选择开始和结束时间"
        :options="options"
        :editable="false"
        style="width: 300px"
      />
    </FormItem>
    <FormItem label="简介" prop="desc">
      <Input
        v-model="formValidate.desc"
        type="textarea"
        :autosize="{minRows: 2,maxRows: 5}"
        placeholder="介绍一下这件宝贝吧..."
      />
    </FormItem>
    <FormItem label="图片" prop="image_src">
      <Upload
        multiple
        type="drag"
        action="/api/goods"
        :format="['jpg', 'png','jpeg']"
        :before-upload="beforeUpload"
        :max-size="5120"
      >
        <!-- 编辑模式 -->
        <div style="padding: 20px 0" v-if="this.$route.query.type && formValidate.image_src">
          <img :src="formValidate.image_src" style="width: 300px" />
        </div>
        <!-- 已上传待发布 -->
        <div style="padding: 20px 0" v-else-if="uploadToggle">
          <Icon type="ios-checkmark-circle-outline" size="52" style="color: #2ecc71"></Icon>
          <p>图片：{{this.formValidate.image_src.name}}</p>
        </div>
        <!-- 未上传 -->
        <div style="padding: 20px 0" v-else>
          <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
          <p v-if="this.formValidate.image_src">图片：{{this.formValidate.image_src.name}}</p>
          <p v-else>请上传一张封面图</p>
        </div>
      </Upload>
    </FormItem>

    <FormItem v-if="this.$route.query.type">
      <Button :loading="loadingStatus" type="primary" @click="handleSubmit('formValidate')">保存</Button>
      <Button @click="$router.back()" style="margin-left: 8px">返回</Button>
    </FormItem>
    <FormItem v-else>
      <Button :loading="loadingStatus" type="primary" @click="handleSubmit('formValidate')">发布</Button>
      <Button @click="handleReset('formValidate')" style="margin-left: 8px">重置</Button>
    </FormItem>
  </Form>
</template>

<script>
import { getBasicInfo } from "../../utils/mixin";

export default {
  name: "publish-bid",
  mixins: [getBasicInfo],
  data() {
    return {
      uploadToggle: false,
      loadingStatus: false,
      kindData: [],
      dateRange: [],
      formValidate: {
        craftsman_id: 0,
        cate_id: null,
        title: "",
        desc: "",
        image_src: null,
        init_price: 0,
        min_gap: 0,
        start_time: "",
        end_time: ""
      },
      options: {
        disabledDate(date) {
          return date && date.valueOf() < Date.now() - 86400000;
        }
      },
      ruleValidate: {
        title: [
          {
            required: true,
            message: "标题不能为空",
            trigger: "change"
          },
          {
            type: "string",
            min: 1,
            message: "请填写至少6个字",
            trigger: "blur"
          }
        ],
        cate_id: [
          {
            required: true,
            message: "种类不能为空",
            type: "number"
          }
        ],

        init_price: [
          {
            required: true,
            type: "number",
            min: 1,
            message: "价格最低为1",
            trigger: "change"
          }
        ],
        min_gap: [
          {
            required: true,
            min: 1,
            type: "number",
            message: "加价幅度最低为1"
          }
        ],
        start_time: [
          {
            required: true,
            message: "竞拍时间不能为空"
          }
        ],
        desc: [
          {
            required: true,
            message: "请输入商品简介",
            trigger: "blur"
          },
          {
            type: "string",
            min: 2,
            message: "请填写至少20个字",
            trigger: "blur"
          }
        ],
        image_src: [
          {
            required: true,
            message: "请至少上传一张实物图"
          }
        ]
      }
    };
  },
  mounted() {
    this.axios
      .get("/api/category")
      .then(res => (this.kindData = res.data))
      .catch(error => console.log("error :", error));
    if (this.$route.query.type == "bid_edit")
      this.axios
        .get(`/api/bid_goods?item=${this.$route.query.bid_id}`)
        .then(res => {
          let bid_goods = res.data;
          this.formValidate.craftsman_id = bid_goods.craftsman_id;
          this.formValidate.cate_id = bid_goods.cate_id;
          this.formValidate.title = bid_goods.title;
          this.formValidate.desc = bid_goods.desc;
          this.formValidate.image_src = bid_goods.image_src;
          this.formValidate.init_price = parseInt(bid_goods.init_price);
          this.formValidate.min_gap = parseInt(bid_goods.min_gap);
          this.formValidate.start_time = bid_goods.start_time;
          this.formValidate.end_time = bid_goods.end_time;
          this.dateRange = [bid_goods.start_time, bid_goods.end_time];
        });
  },
  methods: {
    handleDate(dateRange) {
      this.formValidate.start_time = dateRange[0];
      this.formValidate.end_time = dateRange[1];
    },
    handleSubmit(name) {
      this.$refs[name].validate(valid => {
        if (valid) {
          this.loadingStatus = true;
          let newFormData = new FormData();
          if (this.$route.query.type)
            newFormData.append("id", this.$route.query.bid_id);

          for (let key in this.formValidate) {
            newFormData.append(key, this.formValidate[key]);
          }

          this.axios
            .post("/api/bid_goods", newFormData, {
              headers: {
                "Content-Type": "multipart/form-data"
              }
            })
            .then(res => {
              this.uploadToggle = true;
              this.loadingStatus = false;
              if (this.$route.query.type) {
                this.$Notice.success({
                  title: "保存成功"
                });
                this.$router.push(
                  `/user/${this.getUid}/goods_management?type=bid`
                );
              } else{
                this.$Notice.success({
                  title: "添加竞拍品成功"
                });
              }
                
            })
            .catch(error =>
              this.$Notice.error({
                title: "网络连接失败",
                desc: error
              })
            );
        } else this.$Message.error("信息填写不正确！请更正后重新提交");
      });
    },
    beforeUpload(file) {
      this.formValidate.image_src = file;
      this.formValidate.craftsman_id = this.getCid;
      return false;
    },
    handleReset(name) {
      this.$refs[name].resetFields();
    }
  }
};
</script>
